package com.tree.thread.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * package com.tree.thread
 * description:
 *
 * @author tree
 * @date 2019-10-31 10:40
 */
public class ThreadPoolExecutorTest {

    public static void main(String[] args) {
        int coreSize = 2;
        int maxSize = 4;
        long keepLiveTime = 1L;
        int queueSize = 10;
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue(queueSize);

        ExecutorService executorService = new ThreadPoolExecutor(
                coreSize,maxSize,keepLiveTime, TimeUnit.SECONDS,blockingQueue ,new MyThreadFactory(), new LogPolicy());

        for(int i =0 ; i< 20; i++){
            executorService.execute(new Test2(i));
        }
        executorService.shutdown();
    }


}

class Test2 implements Runnable {
    private int var;
    public Test2(int var ){
        this.var = var;
    }


    @Override
    public void run() {
        try {
            System.out.println("开始执行run方法："+Thread.currentThread().getName()+"_"+var);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

 class LogPolicy implements RejectedExecutionHandler {
    /**
     * Creates an {@code AbortPolicy}.
     */
    public LogPolicy() { }

    /**
     * Always throws RejectedExecutionException.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     * @throws RejectedExecutionException always
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        log(r,e);
    }

     private void log(Runnable r, ThreadPoolExecutor e) {
         System.out.println(Thread.currentThread()+" reject....");
         System.out.println("Task " + r.toString() +
                 " rejected from " +
                 e.toString());

     }
 }

/**
 * The default thread factory
 */
class MyThreadFactory2 implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    MyThreadFactory2() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = "MyThreadFactory2-pool-" +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
